/*
 * Copyright (C) 2009-2010 adrian_007, adrian-007 on o2 point pl
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "stdinc.h"

#define DEFAULT_BUFLEN 512

std::wstring StringToWString(const std::string& s)
{
std::wstring temp(s.length(),L' ');
std::copy(s.begin(), s.end(), temp.begin());
return temp;
};


std::string WStringToString(const std::wstring& s)
{
std::string temp(s.length(), ' ');
std::copy(s.begin(), s.end(), temp.begin());
return temp;
};

std::string reportError(int errorCode, wchar_t* whichFunc)
{
	wchar_t er[20];
	LOG(L"ERROR!");
	swprintf(er, L"%s Error:%d",whichFunc, errorCode);
	LOG(er);
	WSACleanup();
	char e[20];
		sprintf(e,"%s Error:%d",WStringToString(whichFunc),errorCode);
	return e;
};

std::string reply(wchar_t* botId,const wchar_t* input){
	char data[200];
	char request[2048];
	char response[DEFAULT_BUFLEN];
	int ResponseLen = DEFAULT_BUFLEN;
	WSADATA wsaData;
    SOCKET theSocket = INVALID_SOCKET;
	hostent* hostEntry;
	sprintf(data, "botid=%s&input=%s!", WStringToString(botId).c_str(), WStringToString(input).c_str() );

    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
		 return reportError(WSAGetLastError(),L"WSAStartup");
	}
	hostEntry = gethostbyname("www.pandorabots.com");
	if (!hostEntry)	{
		 return reportError(WSAGetLastError(),L"gethostbyname");
	}
	theSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if (theSocket == INVALID_SOCKET){ 
		return reportError(WSAGetLastError(),L"socket");
	}
	SOCKADDR_IN serverInfo;
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
	serverInfo.sin_port = htons(80);		
	iResult = connect(theSocket,(LPSOCKADDR)&serverInfo,sizeof(struct sockaddr));
	if (iResult == SOCKET_ERROR) {
		 return reportError(WSAGetLastError(),L"connect");
	}
	sprintf(request, "POST /pandora/talk-xml HTTP/1.1\r\nHost: www.pandorabots.com\r\nContent-Type: application/x-www-form-urlencoded; charset=utf-8\nContent-Length: %d\r\n\r\n%s\n", strlen(data),data);
	iResult = send(theSocket, request, strlen(request), 0);
	if(iResult == SOCKET_ERROR)
	{
		closesocket(theSocket);
		 return reportError(WSAGetLastError(),L"send");
	}	
	iResult = shutdown(theSocket, SD_SEND);
	if (iResult == SOCKET_ERROR) {
        closesocket(theSocket);
        return reportError(WSAGetLastError(),L"shutdown()");
	}
	do{
		iResult = recv(theSocket, response, ResponseLen, 0);
	}while (iResult > 0 );
	std::string responseStr(response);
	size_t bIdx = responseStr.find("<that>");
	size_t eIdx = responseStr.find("</that>");
	if(bIdx != std::string::npos)
	{
		responseStr = responseStr.substr(bIdx+6, eIdx - bIdx -6);
	}else{
		responseStr = responseStr.find("<message>");
		eIdx = responseStr.find("</message>");
		responseStr = responseStr.substr(bIdx + 9, eIdx - bIdx - 9);
	}
    closesocket(theSocket);
	WSACleanup();
	return responseStr;
};